import pyaudio
import numpy as np
import matplotlib.pyplot as plt

# 配置音频输入
format = pyaudio.paInt16
channels = 1
rate = 44100
chunk_size = 1024

# 创建一个PyAudio对象
audio = pyaudio.PyAudio()

# 打开音频输入流
stream = audio.open(format=format,
                    channels=channels,
                    rate=rate,
                    input=True,
                    frames_per_buffer=chunk_size)

# 创建一个空的波形图
fig, ax = plt.subplots()
x = np.arange(0, 2 * chunk_size, 2)
line, = ax.plot(x, np.random.rand(chunk_size), '-')

# 设置y轴范围
ax.set_ylim(-32768, 32768)

# 开始实时绘制波形
while True:
    # 读取chunk_size个音频帧
    data = stream.read(chunk_size)
    
    # 将音频帧转换为numpy数组
    audio_data = np.frombuffer(data, np.int16)
    
    # 更新波形图数据
    line.set_ydata(audio_data)
    fig.canvas.draw()
    fig.canvas.flush_events()

# 关闭音频流和PyAudio对象
stream.stop_stream()
stream.close()
audio.terminate()
